package pinyin;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinyinUtil {

    private static HanyuPinyinOutputFormat format = null;

    private PinyinUtil() {
    }

    static  {
        format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    }

    public static String getFirstPinYinLetter(String str) throws BadHanyuPinyinOutputFormatCombination {
        if(str == null || str.trim().length() == 0) {
            return "#";
        }
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        char c = str.charAt(0);
        int ascii = (int) c;
        if (ascii < 65) {
            return "#";
        } else if (ascii <= 90) {
            return Character.toString(c).toUpperCase();
        } else if (ascii <= 96) {
            return "#";
        } else if (ascii <= 122) {
            return Character.toString(c).toUpperCase();
        } else if (ascii <= 128) {
            return "#";
        } else {
            String[] t = PinyinHelper.toHanyuPinyinStringArray(c, format);
            if(t.length == 0) {
                return "#";
            }else{
                return Character.toString(t[0].toUpperCase().charAt(0));
            }
        }
    }

    public static void main(String[] args) throws BadHanyuPinyinOutputFormatCombination {
        System.out.println(PinyinUtil.getFirstPinYinLetter("123"));
        System.out.println(PinyinUtil.getFirstPinYinLetter("a吗"));
        System.out.println(PinyinUtil.getFirstPinYinLetter("额"));
        System.out.println(PinyinUtil.getFirstPinYinLetter("1是的"));
        System.out.println(PinyinUtil.getFirstPinYinLetter("A是的"));
    }


}
